import 'package:flutter/material.dart';
import 'package:get/get.dart'; // 引入 GetX
import 'package:rjpb/page/home/inspection/controller/inspection_page_controller.dart'; // 引入控制器
import 'package:jovial_svg/jovial_svg.dart'; //svg
import 'package:matrix_gesture_detector/matrix_gesture_detector.dart';
import 'package:flutter_svg/flutter_svg.dart'; //svg
import 'package:vector_math/vector_math_64.dart'
    as vector_math; // 为 vector_math 指定别名
//气泡框组件
import 'tooltip_widget.dart';
import 'package:rjpb/components/z_icons/z_empty.dart';
//弹窗组件
import 'package:rjpb/page/home/inspection/widgets/point_info_dialog.dart';

class MenuSvgLayout extends StatefulWidget {
  final List<Map<String, dynamic>> menuData;
  final Function(String) onMenuItemSelected;

  const MenuSvgLayout({
    Key? key,
    required this.menuData,
    required this.onMenuItemSelected,
  }) : super(key: key);

  @override
  _MenuSvgLayoutState createState() => _MenuSvgLayoutState();
}

class _MenuSvgLayoutState extends State<MenuSvgLayout> {
  final InspectionPageController _controller =
      Get.find<InspectionPageController>();
  String? selectedId;

  // 将matrixNotifier定义在此处作为成员变量初始化，并添加初始值打印
  final ValueNotifier<Matrix4> matrixNotifier =
      ValueNotifier(Matrix4.identity());
  bool isFirstLoadPointData = true; // 添加这个变量，初始化为 true，表示svg图首次加载
  double localSvgX = 0; // 记录本地svg小图标的x坐标，初始在原点
  double localSvgY = 0; // 记录本地svg小图标的y坐标，初始在原点
  bool isLocalSvgVisible = false; // 用于记录本地svg小图标是否显示，初始为false（隐藏）【选中状态的图标】
  double localSvgWidth = 20; // 本地svg小图标的宽度，可根据实际svg图大小调整【选中状态的图标】
  double localSvgHeight = 20; // 本地svg小图标的高度，可根据实际svg图大小调整【选中状态的图标】
  // 缓存已加载的图标
  Map<String, Widget> pointIconCache = {};
  // 定义一个变量来控制气泡框的显示
  bool isTooltipVisible = false;
  double tooltipLeft = 0;
  double tooltipTop = 0;
  String tooltipContent = '';
  bool isFullScreen = false; // 新增变量，用于记录是否处于全屏状态，初始为 false
  OverlayEntry? _overlayEntry;

  @override
  void initState() {
    super.initState();
    if (widget.menuData.isNotEmpty) {
      selectedId = _getFirstLeafId(widget.menuData.first);
      if (selectedId != null) {
        // 调用菜单项选中逻辑，加载对应的 SVG 图
        widget.onMenuItemSelected(selectedId!);
      }
    }
  }

  String? _getFirstLeafId(Map<String, dynamic> menu) {
    if (menu['children'] == null || menu['children'].isEmpty) {
      return menu['id'];
    }
    return _getFirstLeafId(menu['children'].first);
  }

  void _onMenuItemTap(String id) {
    setState(() {
      selectedId = id;
      //当切换三级菜单时，清空一些数据
      isTooltipVisible = false; // 隐藏气泡框
      tooltipContent = "";
      tooltipLeft = 0;
      tooltipTop = 0;
      isLocalSvgVisible = false; // 隐藏本地svg小图标
      matrixNotifier.value = Matrix4.identity();
    });
    widget.onMenuItemSelected(id);
  }

  IconData _getIconForLevel(int level, bool isSelected) {
    switch (level) {
      case 0:
        return isSelected
            ? Icons.account_balance
            : Icons.account_balance_outlined;
      case 1:
        return isSelected ? Icons.business : Icons.business_outlined;
      case 2:
        return isSelected ? Icons.view_agenda : Icons.view_agenda_outlined;
      default:
        return isSelected ? Icons.folder_open : Icons.folder_outlined;
    }
  }

  //以下是svg图处理
  Matrix4 removeRotation(Matrix4 matrix) {
    Matrix4 newMatrix = Matrix4.identity()
      ..setEntry(0, 0, matrix.storage[0]) // 保留缩放X
      ..setEntry(1, 1, matrix.storage[5]) // 保留缩放Y
      ..setEntry(0, 3, matrix.storage[12]) // 保留平移X
      ..setEntry(1, 3, matrix.storage[13]) // 保留平移Y
      ..setEntry(0, 1, 0) // 移除旋转
      ..setEntry(1, 0, 0); // 移除旋转
    return newMatrix;
  }

  Widget loadLocalSvgImage() {
    print("要显示原点了");
    // 这里暂时返回一个简单占位的SizedBox，实际需要根据加载逻辑替换
    return SizedBox(
      width: 10,
      height: 10,
      // child: Text('本地SVG图片'),
      child: SvgPicture.asset(
        'assets/checked.svg', // 替换为你的SVG图像路径，如果是平板 /assets/test7.svg
        height: 10, // 设置SVG图像高度
        width: 10, // 设置SVG图像宽度
        // fit: BoxFit.contain, // 适应容器
        cacheColorFilter: false,
      ),
    );
  }

  // 提取旋转和平移的矩阵
  Matrix4 removeScale(Matrix4 originalMatrix) {
    // 提取缩放比例
    double scaleX = originalMatrix.storage[0]; // (0, 0)
    double scaleY = originalMatrix.storage[5]; // (1, 1)

    // 去掉缩放，创建新矩阵
    Matrix4 newMatrix = Matrix4.identity()
      ..setEntry(0, 0, originalMatrix.storage[0] / scaleX) // X方向归一化
      ..setEntry(0, 1, originalMatrix.storage[1] / scaleX) // 旋转部分
      ..setEntry(1, 0, originalMatrix.storage[4] / scaleY) // 旋转部分
      ..setEntry(1, 1, originalMatrix.storage[5] / scaleY) // Y方向归一化
      ..setEntry(0, 3, originalMatrix.storage[12]) // 平移X
      ..setEntry(1, 3, originalMatrix.storage[13]); // 平移Y

    return newMatrix;
  }

  Future<Widget> _loadPointIcon(Map<String, dynamic> point) async {
    String url = point['typeLibraryUrl'];

    // 检查缓存中是否已有该图标
    if (pointIconCache.containsKey(url)) {
      return pointIconCache[url]!;
    }

    try {
      // 如果缓存中没有，发起请求并加载SVG
      ScalableImage? scalableImage =
          await ScalableImage.fromSvgHttpUrl(Uri.parse(url));
      Widget icon = SizedBox(
        width: 14, //之前是5
        height: 14,
        child: ScalableImageWidget(si: scalableImage!),
      );

      // 将加载的图标缓存
      pointIconCache[url] = icon;

      return icon;
    } catch (e) {
      print('加载点位图标SVG出错: $e');
      return SizedBox(); // 加载失败时返回空组件
    }
  }

  //以上是svg图处理

  Widget _buildMenu(List<Map<String, dynamic>> menuData, {int level = 0}) {
    if (_controller.MenuDataEmpty.value) {
      print("进入空状态了");
      return SizedBox.expand(
        child: Material(
          color: Colors.transparent, // 避免覆盖背景
          child: ZEmpty(gapH: 0),
        ),
      );
    }
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: menuData.length,
      itemBuilder: (context, index) {
        final item = menuData[index];
        final isSelected = selectedId == item['id'];
        final hasChildren =
            item['children'] != null && (item['children'] as List).isNotEmpty;

        if (!hasChildren) {
          return _buildMenuItem(item, isSelected, hasChildren, level);
        }

        return Theme(
          data: Theme.of(context).copyWith(
            dividerColor: Colors.transparent,
          ),
          child: ExpansionTile(
            key: ValueKey(item['id']),
            initiallyExpanded: true,
            maintainState: true,
            tilePadding: EdgeInsets.only(left: level * 16.0),
            title: _buildTileContent(item, isSelected, hasChildren, level),
            children: [
              _buildMenu(
                List<Map<String, dynamic>>.from(item['children']),
                level: level + 1,
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildMenuItem(
      Map<String, dynamic> item, bool isSelected, bool hasChildren, int level) {
    return Container(
      margin: EdgeInsets.only(left: level * 16.0, bottom: 4),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        gradient: isSelected
            ? LinearGradient(
                colors: [Colors.blue.shade600, Colors.blue.shade400],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
              )
            : null,
        boxShadow: isSelected
            ? [
                BoxShadow(
                  color: Colors.blue.withOpacity(0.3),
                  blurRadius: 6,
                  spreadRadius: 1,
                  offset: Offset(2, 2),
                )
              ]
            : null,
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _onMenuItemTap(item['id']),
          borderRadius: BorderRadius.circular(8),
          splashColor: Colors.blue.withOpacity(0.2),
          highlightColor: Colors.blue.withOpacity(0.1),
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            child: Row(
              children: [
                Icon(
                  _getIconForLevel(level, isSelected),
                  color: isSelected ? Colors.white : Colors.blue.shade600,
                  size: 18,
                ),
                SizedBox(width: 12),
                Expanded(
                  child: Text(
                    item['name'] ?? '未知',
                    style: TextStyle(
                      color: isSelected ? Colors.white : Colors.grey.shade800,
                      fontWeight:
                          isSelected ? FontWeight.w600 : FontWeight.w500,
                      fontSize: 14,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTileContent(
      Map<String, dynamic> item, bool isSelected, bool hasChildren, int level) {
    return Row(
      children: [
        Icon(
          _getIconForLevel(level, isSelected),
          color: isSelected ? Colors.white : Colors.blue.shade600,
          size: 18,
        ),
        SizedBox(width: 12),
        Expanded(
          child: Text(
            item['name'] ?? '未知',
            style: TextStyle(
              color: isSelected ? Colors.white : Colors.grey.shade800,
              fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
              fontSize: 14,
            ),
          ),
        ),
      ],
    );
  }

//以下是svg图处理
  Widget _buildPointIconWidget(Map<String, dynamic> point) {
    return FutureBuilder<Widget>(
      future: _loadPointIcon(point),
      builder: (BuildContext context, AsyncSnapshot<Widget> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return Text('加载点位图标出现错误');
          }
          return snapshot.data!;
        }
        return SizedBox();
      },
    );
  }

  Widget _buildRightContent() {
    print('菜单选中的值id: ${_controller.selectedMenuId.value}');

    return Obx(() {
      final svgString = _controller.selectedSvgString.value;
      final pointData = _controller.pointData;
      final isLoading = _controller.isLoadingSvg.value;

      // 显示加载中的状态
      if (isLoading) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(
                width: 100, // 控制加载动画的大小
                height: 100,
                child: Image.asset('assets/loading.gif'), // 你的loading.gif
              ),
              SizedBox(height: 20),
              Text(
                '加载中...',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
        );
      }

      if (svgString != null) {
        return FutureBuilder<ScalableImage>(
          future: Future.value(ScalableImage.fromSvgString(svgString!)),
          builder:
              (BuildContext context, AsyncSnapshot<ScalableImage> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.error_outline, color: Colors.red, size: 50),
                      SizedBox(height: 16),
                      Text(
                        '加载SVG失败',
                        style: TextStyle(fontSize: 16, color: Colors.red),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '${snapshot.error}',
                        style: TextStyle(fontSize: 14, color: Colors.grey),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                );
              }

              // 获取SVG图像的宽高并打印，提供默认值0.0
              double originalWidth = snapshot.data!.width ?? 0.0;
              double originalHeight = snapshot.data!.height ?? 0.0;
              print('SVG图像原始的宽度：$originalWidth');
              print('SVG图像原始的高度：$originalHeight');

              return LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
                  double parentWidth = constraints.maxWidth;
                  double parentHeight = constraints.maxHeight;

                  // 计算缩小后的宽高，缩放比例设为0.4
                  double scaledWidth = originalWidth * 0.6;
                  double scaledHeight = originalHeight * 0.6;
                  print('SVG图像缩小后的宽度：$scaledWidth');
                  print('SVG图像缩小后的高度：$scaledHeight');

                  return Stack(
                    children: [
                      // 外部容器用于识别缩放和移动操作
                      Container(
                        width: parentWidth, // 设置为父容器的宽度
                        height: parentHeight, // 设置为父容器的高度
                        alignment: Alignment.topLeft, // 确保父级容器内的子元素从左上角开始
                        child: MatrixGestureDetector(
                          onMatrixUpdate: (Matrix4 matrix,
                              Matrix4 translationMatrix,
                              Matrix4 scaleMatrix,
                              Matrix4 rotationMatrix) {
                            print(
                                'MatrixGestureDetector - onMatrixUpdate triggered');
                            print('Matrix4 Scale Matrix: $scaleMatrix');
                            double scaleX = scaleMatrix.storage[0]; // 缩放的X方向比例
                            double scaleY = scaleMatrix.storage[5]; // 缩放的Y方向比例
                            print('当前缩放比例 ScaleX: $scaleX, ScaleY: $scaleY');
                            // 移除旋转
                            Matrix4 modifiedMatrix = removeRotation(matrix);

                            // 更新矩阵
                            matrixNotifier.value = modifiedMatrix;
                            isFirstLoadPointData = false; // 标记已完成首次加载
                          },
                          child: AnimatedBuilder(
                            animation: matrixNotifier,
                            builder: (BuildContext context, Widget? child) {
                              return Transform(
                                transform: matrixNotifier.value,
                                alignment: Alignment.topLeft, // 设置变换基准为左上角
                                child: SingleChildScrollView(
                                  child: Container(
                                    width: parentWidth, // 使图片容器宽度和父容器一致
                                    height: parentHeight, // 使图片容器高度和父容器一致
                                    child: Stack(
                                      children: [
                                        // SVG 图
                                        Positioned(
                                          left: 0,
                                          top: 0,
                                          child: SizedBox(
                                            width: scaledWidth, // 保持图片的宽高不变
                                            height: scaledHeight, // 保持图片的宽高不变
                                            child: ScalableImageWidget(
                                              si: snapshot.data!,
                                            ),
                                          ),
                                        ),
                                        // 在原点添加本地svg小图标，初始隐藏（透明度为0）
                                        Positioned(
                                          left: localSvgX,
                                          top: localSvgY,
                                          child: Opacity(
                                            opacity: isLocalSvgVisible
                                                ? 1
                                                : 0, // 根据显示状态设置透明度，这里改回正确的隐藏逻辑
                                            child: SizedBox(
                                              width: localSvgWidth,
                                              height: localSvgHeight,
                                              child: Transform.translate(
                                                offset: Offset(
                                                  -localSvgWidth / 2 +
                                                      7, // 将图标沿x轴向左平移宽度的一半，使其中心位于指定x坐标
                                                  -localSvgHeight / 2 +
                                                      7, // 将图标沿y轴向上平移高度的一半，使其中心位于指定y坐标
                                                ),
                                                child:
                                                    loadLocalSvgImage(), // 传入正确的本地svg图片路径
                                              ),
                                            ),
                                          ),
                                        ),
                                        // 点位逻辑
                                        if (pointData.isNotEmpty)
                                          ...pointData.map((point) {
                                            double x = (point['xaxis'] !=
                                                        null &&
                                                    point['xaxis'] is String)
                                                ? double.tryParse(
                                                        point['xaxis']) ??
                                                    0
                                                : 0;
                                            double y = (point['yaxis'] !=
                                                        null &&
                                                    point['yaxis'] is String)
                                                ? double.tryParse(
                                                        point['yaxis']) ??
                                                    0
                                                : 0;
                                            x = x * 0.6;
                                            y = y * 0.6;

                                            // 不再乘以缩放比例，确保点位在图片内正确显示
                                            final vector_math.Vector4
                                                pointVector =
                                                vector_math.Vector4(x, y, 0, 0);

                                            // 使用变换矩阵来更新点位坐标
                                            final Matrix4 transformedMatrix =
                                                removeScale(
                                                    matrixNotifier.value);

                                            // 使用新矩阵进行点位变换
                                            final vector_math.Vector4
                                                transformedVector4 =
                                                transformedMatrix
                                                    .transform(pointVector);
                                            print(
                                                "变换后的坐标: (${transformedVector4.x}, ${transformedVector4.y})");

                                            double transformedX =
                                                transformedVector4.x;
                                            double transformedY =
                                                transformedVector4.y;

                                            // 构建点位图标部分
                                            Widget pointIconWidget =
                                                _buildPointIconWidget(point);

                                            return Positioned(
                                              left: transformedX,
                                              top: transformedY,
                                              child: GestureDetector(
                                                // onTap: () {
                                                //   setState(() {
                                                //     // 更新本地svg小图标的位置和显示状态
                                                //     localSvgX = transformedX;
                                                //     localSvgY = transformedY;
                                                //     print(
                                                //         "此刻点击的坐标是，${localSvgX},${localSvgY}");
                                                //     isLocalSvgVisible = true;

                                                //     // 设置气泡框的内容和位置
                                                //     tooltipLeft = transformedX +
                                                //         15; // 气泡框距点位有点偏移
                                                //     tooltipTop = transformedY -
                                                //         10; // 气泡框距离点位一定距离
                                                //     tooltipContent =
                                                //         '地址：${point['loopNum']}-${point['dotNum']}\n类型：${point['svgType']}';
                                                //     isTooltipVisible =
                                                //         true; // 显示气泡框
                                                //   });
                                                // },
                                                onTap: () async {
                                                  print("点击了点位图标");

                                                  final String patrolMark =
                                                      point['patrolMark']
                                                          .toString();
                                                  final String patrolItemId =
                                                      point['id'].toString();

                                                  try {
                                                    final content =
                                                        await _controller
                                                            .fetchTooltipContent(
                                                                patrolMark,
                                                                patrolItemId);

                                                    setState(() {
                                                      localSvgX = transformedX;
                                                      localSvgY = transformedY;
                                                      print(
                                                          "此刻点击的坐标是，${localSvgX},${localSvgY}");
                                                      isLocalSvgVisible = true;
                                                    });

                                                    showDialog(
                                                      context: context,
                                                      builder: (context) =>
                                                          PointInfoDialog(
                                                        content: content,
                                                        patrolMark: patrolMark,
                                                      ),
                                                    );
                                                  } catch (e) {
                                                    // 如果请求失败也显示未分配任务
                                                    showDialog(
                                                      context: context,
                                                      builder: (context) =>
                                                          AlertDialog(
                                                        title: const Text('提示'),
                                                        content: const Text(
                                                            '该巡检点暂未分配任务'),
                                                        actions: [
                                                          TextButton(
                                                            onPressed: () =>
                                                                Navigator.of(
                                                                        context)
                                                                    .pop(),
                                                            child: const Text(
                                                                '确定'),
                                                          ),
                                                        ],
                                                      ),
                                                    );
                                                  }
                                                },
                                                child: pointIconWidget,
                                              ),
                                            );
                                          }).toList(),

                                        // 显示气泡框
                                        if (isTooltipVisible)
                                          TooltipWidget(
                                            content: tooltipContent,
                                            left: tooltipLeft,
                                            top: tooltipTop,
                                          ),
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                      ),

                      // 在右上角添加全屏/恢复按钮
                      Positioned(
                        top: 10,
                        right: 10,
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              isFullScreen = !isFullScreen;
                              _overlayEntry?.remove();
                              _overlayEntry = null;
                            });
                          },
                          child: Icon(
                            isFullScreen
                                ? Icons.fullscreen_exit
                                : Icons.fullscreen,
                            color: Colors.black,
                          ),
                        ),
                      ),
                    ],
                  );
                },
              );
            } else {
              // FutureBuilder 加载中的状态
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 80,
                      height: 80,
                      child: Image.asset('assets/loading.gif'),
                    ),
                    SizedBox(height: 16),
                    Text(
                      '解析SVG中...',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              );
            }
          },
        );
      }

      return Center(
        child: Image.asset(
          'assets/entry.png', // 替换为实际的png图片路径
          fit: BoxFit.contain, // 让图片保持比例并适应容器，可根据需求调整
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        // 左侧菜单区域 - 固定高度
        if (!isFullScreen)
          Expanded(
            flex: 3,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: MediaQuery.of(context).size.height * 0.8, // 设置最小高度
              ),
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.08),
                      blurRadius: 12,
                      spreadRadius: 4,
                      offset: Offset(0, 4),
                    ),
                  ],
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: Material(
                    color: Colors.white,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      // child: SingleChildScrollView(
                      //   child: _buildMenu(widget.menuData),
                      // ),
                      child: SingleChildScrollView(
                        child: widget.menuData.isEmpty
                            ? Center(
                                child: Image.asset(
                                  'assets/entry.png', // 替换为实际的png图片路径
                                  fit: BoxFit.contain, // 让图片保持比例并适应容器，可根据需求调整
                                ),
                              )
                            : _buildMenu(widget.menuData),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        SizedBox(width: 16),

        Expanded(
          flex: 7,
          child: Card(
            elevation: 5, // 设置阴影
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12), // 设置圆角
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12), // 确保内容也有圆角
              child: Column(
                children: [
                  //如果后期需要加搜索 可以在这里加入搜索框，上面为2  下面为8
                  // Expanded(
                  //   flex: 2, // 20%
                  //   child: Container(
                  //     color: Colors.yellow,
                  //     // child: _buildUpperContent(),
                  //   ),
                  // ),
                  Expanded(
                    flex: 1,
                    child: _buildRightContent(),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}
